﻿package src.com.rageSteroid {
	import flash.display.Sprite
	import com.greensock.*;
	import flash.events.Event;
	import flash.events.*;
	
	public class Main extends Sprite{

		private const STAGE_WIDTH  : int = 550;
		private const STAGE_HEIGHT : int = 400;
		private var _hero:Hero;
		private var _allLaser:Array = [];
		private var _allAsteroid:Array = [];
		
		public function Main(){
			this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
		}
		private function onAddedToStage(event:Event):void{
			this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			
			
			drawBg();
			spawnHero();
			spawnAste();
			
			for (var i:int=0; i<=5; i++) {
				spawnAste();
			}	
			stage.addEventListener(MouseEvent.CLICK,piouPiou);
		}
		 //Fait apparaître des Astéroides au random
		private function spawnAste():void	{
				var _astero:Asteroid;
				_astero = new Asteroid(Math.floor(Math.random()*50));
				_astero.x = (Math.floor(Math.random()*550));/*STAGE_WIDTH>>1;*/
				_astero.y = (Math.floor(Math.random()*400));/*STAGE_WIDTH>>1+250;*/
				addChild(_astero);
				_allAsteroid.push(_astero);		
				
		}
		
		private function piouPiou(event:Event = null):void {
			var laser:Laser = new Laser();
			_allLaser.push(laser);
			laser.x = _hero.x;
			laser.y = _hero.y;
			addChild(laser);
			//TweenLite.to(laser,0.4,{x:0,y:0});
			TweenMax.to(laser,0.4,{x:laser.parent.mouseX,y:laser.parent.mouseY,onComplete:checkForAsteroid, onCompleteParams:[laser]});
		}
		private function checkForAsteroid(laser:Laser):void{
			for (var asteroid:int=0; asteroid < _allAsteroid.length; asteroid++)
				if(laser.hitTestObject(_allAsteroid[asteroid])){
					_allAsteroid[asteroid].parent.removeChild(_allAsteroid[asteroid]);
					trace("FUCK TA MERE");
					spawnAste();
					
				}
			
			laser.parent.removeChild(laser);
		}
		
		private function spawnHero():void	{ //Fait spawn un vaisseau
			_hero = new Hero();
			_hero.x = STAGE_WIDTH  >> 1;
			_hero.y = STAGE_HEIGHT >> 1;
			_hero.y = STAGE_HEIGHT>>1;
			addChild(_hero);
			
		}
		
		private function drawBg():void{
			this.graphics.beginFill(0x000000);
			this.graphics.drawRect(0,0,STAGE_WIDTH,STAGE_HEIGHT);
		}
	}	
}